/*
 * CreateDemo.cpp
 *
 *  Created on: 2011-8-10
 *      Author: hywie
 */

#include "CreateDemo.h"

void createSocket(DBClass *db)
{
	int serv_fd;
	struct sockaddr_in serv_addr;		//在netinet/in.h中定义

	serv_fd = socket(AF_INET, SOCK_STREAM, 0);	//socket()在sys/socket.h中定义

	if(serv_fd < 0)		//建立套接字失败
	{
		cout<<"创建套接字失败..."<<endl;
		return ;
	}

	serv_addr.sin_family	= AF_INET;				//AF_INET在sys/socket.h中声明
	serv_addr.sin_port = htons(PORT);			//htons()在netinet/in.h中定义
	serv_addr.sin_addr.s_addr = INADDR_ANY;	//inet_addr()在arpa/inet.h中定义
	memset(&(serv_addr.sin_zero), 0, 8);		//memset()在string.h中定义

	//绑定套接字和服务器地址
	if(bind(serv_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
	{
		cout<<"绑定套接字失败..."<<endl;
		close(serv_fd);	//绑定失败,关闭套接字
		return ;
	}

	db->setServ_fd(serv_fd);	//设置套接字
	ClientClass *client = new ClientClass(serv_fd, db);	//设置共有DBClass类对象
	listenSocket(client);		//监听套接字
}

void listenSocket(ClientClass *client)
{
	int serv_fd;
	serv_fd = client->getSock_fd();		//得到要进行监听的套接字
	if(listen(serv_fd, MAX_CLIENT_NUM) != 0)	//监听失败
	{
		cout<<"监听失败"<<endl;
		close(serv_fd);	//关闭套接字
		return ;
	}

	int client_fd;
	pthread_t tid;
	struct sockaddr_in client_addr;		//客户端地址
	socklen_t len;
	len = sizeof(client_addr);

	while(1)
	{
		client_fd = accept(serv_fd, (struct sockaddr *)&client_addr, &len);	//接收客户端连接请求
		if(client_fd < 0)		//连接失败
		{
			cout<<"接收客户连接失败..."<<endl;
		}
		else
		{
			//为新连接的客户端建立一个ClientClass对象,并进行赋值
			ClientClass *newClient = new ClientClass(client_fd, client->getDBClass());
			pthread_create(&tid, NULL, thread_recv, newClient);	//为新连接的客户端新建线程,用以信息交互
			client->getDBClass()->threadAdd(tid);	//记录该线程号
		}
	}
}

void radioFunc(int sock_fd, struct def_msg msg)		//向指定的套接字发送一条消息
{
	send(sock_fd, (char *)&msg, sizeof(msg), 0);
}
